<?php
/**
 * Created by 王跃达.
 * User: 小马出行
 * Date: 2017/8/25
 * Time: 10:07
 */

namespace my;

use Alipay\AlipayTradeFastpayRefundQueryRequest;
use Alipay\AlipayTradeRefundRequest;
use Alipay\AopClient;
use Alipay\AlipayTradeAppPayRequest;
use my\Define;
use my\wechatAppPay;
use think\Cache;
use think\Env;
use think\Loader;
use OSS\OssClient;
use OSS\Core\OssException;
use qrcode\QRcode;

class Tools
{
	/**
	 * 发送短信
	 * @param $phone
	 * @param $content //短信内容
	 * @param $type //短信模板对应内容
	 * @return mixed
	* AccessKey ID： LTAIiSSFJICqDnPt
	 *AccessKey Secret:  2wQ2L8GDhZlWPtaadccqG5zGmZzAkE
	 */
	 function sendMes1($phone, $content=array(), $type = 1)
    {
        Loader::import('Alidayu.TopSdk', EXTEND_PATH);
        $c = new \TopClient;
        $c->appkey = "LTAI5tQ4Kh7FV4T8sEhGNUg5";  //申请的appkey
        $c->secretKey = "8jUPVPmwrBTk3KZZSYWENBCuCG0NVc";      //申请的secreKey
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $req->setExtend("123456");
        $req->setSmsType("normal");
        $req->setSmsFreeSignName("人民出行");  //测试名
        $code = $content;
        $req->setSmsParam("{\"code\":\"" . $code . "\"}"); //验证码
        $req->setSmsTemplateCode("SMS_143065041");//模板ID

        $req->setRecNum($phone);//发送电话号码
		return $resp = $c->execute($req);
    }
    function sendMes99()
    {
        Loader::import('Alidayu.TopSdk', EXTEND_PATH);
        $c = new \TopClient;
        $c->appkey = "LTAI4G54Mda2cNHoBMEcQJ6G";  //申请的appkey
        $c->secretKey = "ReKduLng5AOJQfCF7r5MbWrtePhOd1";      //申请的secreKey
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $req->setExtend("123456");
        $req->setSmsType("normal");
        $req->setSmsFreeSignName("小马出行");  //测试名
        $code = "1234";
        $req->setSmsParam("{\"code\":\"" . $code . "\",\"product\":\"小马出行\"}"); //验证码
        $req->setSmsTemplateCode("SMS_66680212");//模板ID
        $req->setRecNum("18305540289");//发送电话号码
        $resp = $c->execute($req);
        echo "<pre>";
        print_r($resp);
        exit;
    }
	public static function sendMes($phone, $content=array(), $type = 1)
	{

		Loader::import('Alidayu.TopSdk', EXTEND_PATH);
        $c = new \TopClient;

         $c->appkey = Define::SMS_KEY;  //申请的appkey
         $c->secretKey = Define::SMS_SECRET;      //申请的secreKey

        //$c->appkey = 'LTAIiSSFJICqDnPt';  //申请的appkey
        //$c->secretKey = '2wQ2L8GDhZlWPtaadccqG5zGmZzAkE';      //申请的secreKey

		$req = new \AlibabaAliqinFcSmsNumSendRequest;
		$req->setExtend("123456");
		$req->setSmsType("normal");
		$req->setSmsFreeSignName("人民出行");  //测试名
		// 生成验证码
		if ($type == 1) {
			$code = $content;
			$req->setSmsParam("{\"code\":\"" . $code . "\",\"product\":\"登录\"}"); //验证码
			$req->setSmsTemplateCode("SMS_66680212");//模板ID
			//$t="验证码";
		} elseif ($type == 2) {
			$starttime = $content['starttime'];
			$startaddress = $content['startaddress'];
			$req->setSmsParam("{\"starttime\":\"" . $starttime . "\",\"startaddress\":\"" . $startaddress . "\"}"); //通知司机新订单
			$req->setSmsTemplateCode("SMS_66730335");//模板ID
			// $t="通知司机新订单";
		} elseif ($type == 3) {
			$starttime = $content['starttime'];
			$startaddress = $content['startaddress'];
			$count = $content['count'];
			$req->setSmsParam("{\"starttime\":\"" . $starttime . "\",\"startaddress\":\"" . $startaddress . "\",\"count\":\"" . $count . "\"}"); //通知客服新订单
			$req->setSmsTemplateCode("SMS_66765395");//模板ID
			//$t="通知客服新订单";
		} elseif ($type == 4) {
			//请注意有上车扫码的乘客退单，订单号为:${osn}
			$osn = $content['osn'];
			$req->setSmsParam("{\"osn\":\"" . $osn . "\"}"); //通知客服上车付款退单
			$req->setSmsTemplateCode("SMS_66685361");//模板ID
			// $t="通知客服上车付款退单";
		} elseif ($type == 5) {
			$osn = $content['osn'];
			$req->setSmsParam("{\"osn\":\"" . $osn . "\"}"); //通知客服付款后的退单
			$req->setSmsTemplateCode("SMS_66835351");//模板ID
		} elseif ($type == 6) {
			$money = $content['money'];
			$req->setSmsParam("{\"xmcoupon\":\"" . $money . "\"}"); //通知客服付款后的退单
			$req->setSmsTemplateCode("SMS_69750157");//模板ID
			// $t="通知乘客优惠券";
		} elseif ($type == 7) {
			$name = $content['name'];
			$req->setSmsParam("{\"name\":\"" . $name . "\"}"); //通知客服付款后的退单
			$req->setSmsTemplateCode("SMS_70075337");//模板ID
			//$t="通知司机招募";
		} elseif ($type == 8) {
			$month = $content['month'];
			$day = $content['day'];
			$hour = $content['hour'];
			$minute = $content['minute'];
			$name = $content['name'];
			$price = $content['price'];
			$money = $content['money'];
			$req->
			setSmsParam("{\"month\":\"" . $month . "\",\"day\":\"" . $day . "\",\"hour\":\"" . $hour . "\",\"minute\":\"" . $minute . "\",\"name\":\"" . $name . "\",\"price\":\"" . $price . "\",\"money\":\"" . $money . "\"}"); //通知客服新订单
			$req->setSmsTemplateCode("SMS_73805011");//模板ID
			//$t="通知司机奖励";
		}elseif ($type == 9) {
			$driver = $content;
			$req->setSmsParam("{\"driver\":\"" . $driver . "\",\"product\":\"小马出行\"}"); //审核通知
			$req->setSmsTemplateCode("SMS_118765058");//模板ID
			//$t="司机认证审核通过";
		}
		elseif ($type == 10) {
			$driver = $content;
			$req->setSmsParam("{\"driver\":\"" . $driver . "\",\"product\":\"小马出行\"}"); //审核通知
			$req->setSmsTemplateCode("SMS_118560060");//模板ID
			//$t="司机认证审核未通过";
		}
		elseif ($type == 11) {
			$coach = $content;
			$req->setSmsParam("{\"driver\":\"" . $coach . "\",\"product\":\"小马出行\"}"); //教练提交资料通知
			$req->setSmsTemplateCode("SMS_123485012");//模板ID
			//$t="教练提交资料通知";
		}
		elseif ($type == 12) {
			$coach = $content;
			$req->setSmsParam("{\"driver\":\"" . $coach . "\",\"product\":\"小马出行\"}"); //教练审核通知
			$req->setSmsTemplateCode("SMS_123305017");//模板ID
			//$t="司机认证审核通过";
		}
		elseif ($type == 13) {
			$coach = $content;
			$req->setSmsParam("{\"driver\":\"" . $coach . "\",\"product\":\"小马出行\"}"); //教练审核通知
			$req->setSmsTemplateCode("SMS_123310024");//模板ID
			//$t="司机认证审核未通过";
		}
		elseif ($type==14){
			$req->setSmsParam("{\"driver\":\"" . $content . "\",\"product\":\"小马出行\"}");
			$req->setSmsTemplateCode("SMS_124315030");//模板ID
			$t="网约车司机提交资料成功提醒";
		}
		elseif ($type==15){
			$req->setSmsParam("{\"driver\":\"" . $content['name']."\",\"password\":\"".$content['password']."\",\"product\":\"小马出行\"}");
			$req->setSmsTemplateCode("SMS_124360041");//模板ID
			$t="司机审核认证通过";
		}
		elseif ($type==16){
			$req->setSmsParam("{\"driver\":\"" . $content . "\",\"product\":\"小马出行\"}");
			$req->setSmsTemplateCode("SMS_124420033");//模板ID
			$t="司机审核认证未通过";
		}
		elseif ($type==17){//给报警人发送
			$req->setSmsParam("{\"phone\":\"" . $phone ."\",\"product\":\"小马出行\"}");
			$req->setSmsTemplateCode("SMS_125930007");//模板ID
			$t="乘客紧急求助已成功短信提醒";
		}
		elseif ($type==18){//给后台客服发送短信提醒
			$req->setSmsParam("{\"phone\":\"" . $content . "\",\"product\":\"小马出行\"}");
			$req->setSmsTemplateCode("SMS_125740009");//模板ID
			$t="一键报警信息提醒";
		}
		elseif ($type==20){//给后台客服发送短信提醒
			$req->setSmsParam("{\"phone\":\"" . $phone . "\",\"name\":\"" . $content . "\",\"product\":\"小马出行\"}");
			$req->setSmsTemplateCode("SMS_125765019");//模板ID
			$t="投诉反馈信息提醒";
		}
		elseif ($type==21){//给后台客服发送短信提醒
			$req->setSmsParam("{\"phone\":\"" . $phone ."\",\"product\":\"小马出行\"}");
			$req->setSmsTemplateCode("SMS_126035058");//模板ID
			$t="系统自动取消订单信息提醒";
		}
		elseif ($type==22){//给推荐人发送短信通知领取礼品(驾校招生)
			$req->setSmsParam("{\"name\":\"" . $content['name'] ."\",\"phone\":\"" . $content['phone'] . "\",\"product\":\"小马出行\"}");
			$req->setSmsTemplateCode("SMS_128490031");//模板ID
			$t="给推荐人发送短信通知领取礼品";
		}
		elseif ($type==23){
			$req->setSmsParam("{\"driver\":\"" . $phone . "\",\"product\":\"小马出行\"}"); //审核通知
			$req->setSmsTemplateCode("SMS_156282040");//模板ID
			$t="顺风车车主审核未通过";
		}
		elseif ($type==24){
			$req->setSmsParam("{\"driver\":\"" . $phone . "\",\"product\":\"小马出行\"}"); //审核通知
			//$req->setSmsTemplateCode("SMS_156282039");//模板ID
            $req->setSmsTemplateCode("SMS_162635778");//模板ID
			$t="顺风车车主审核通过";
		}
        elseif($type==99){
            $req->setSmsParam("{\"driver\":\"" . $phone . "\",\"product\":\"小马出行\"}"); //审核通知
            $req->setSmsTemplateCode("SMS_170840416");//模板ID
            $t="快车车主审核通过";
        }
        elseif($type==101){
            $req->setSmsParam("{\"driver\":\"" . $phone . "\",\"product\":\"小马出行\"}"); //审核通知
            $req->setSmsTemplateCode("SMS_170836051");//模板ID
            $t="认证资料审核通过";
        }
		elseif ($type==30){
            $name = $content;
            $req->setSmsParam("{\"name\":\"" . $name . "\"}"); //  提现成功时通知
            $req->setSmsTemplateCode("SMS_162546030");//模板ID
            $t="用户提现成功";
        }
        elseif ($type==31){
            $name = $content;
            $req->setSmsParam("{\"name\":\"" . $name . "\"}"); //  提现失败时通知
            $req->setSmsTemplateCode("SMS_162523328");//模板ID
            $t="用户提现失败";
        }
        elseif ($type==32){
            $start_time = $content['start_time'];
            $start_name = $content['start_name'];
            $arrive_name = $content['arrive_name'];
            $req->setSmsParam("{\"start_time\":\"" . $start_time . "\",\"start_name\":\"" . $start_name .  "\",\"arrive_name\":\"" . $arrive_name . "\",\"product\":\"小马出行\"}"); //  城际派单给司机时通知
            $req->setSmsTemplateCode("SMS_163435953");//模板ID
            $t="城际派单给司机";
        }
        elseif ($type==33){
            $start_time = $content['start_time'];
            $start_name = $content['start_name'];
            $req->setSmsParam("{\"start_time\":\"" . $start_time . "\",\"start_name\":\"" . $start_name . "\",\"product\":\"小马出行\"}"); //  城际派单给乘客时通知
            $req->setSmsTemplateCode("SMS_163436199");//模板ID
            $t="城际派单给乘客";
        }
        elseif ($type==34){
            $start_time = $content['start_time'];
            $start_name = $content['start_name'];
            $req->setSmsParam("{\"start_time\":\"" . $start_time . "\",\"start_name\":\"" . $start_name . "\",\"product\":\"小马出行\"}"); //  城际订单指派单被取消给司机时通知
            $req->setSmsTemplateCode("SMS_163430938");//模板ID
            $t="城际订单指派单被取消给司机";
        }
        elseif ($type==35){
            $start_time = $content['start_time'];
            $start_name = $content['start_name'];
            $req->setSmsParam("{\"start_time\":\"" . $start_time . "\",\"start_name\":\"" . $start_name . "\",\"product\":\"小马出行\"}"); //  城际订单指派单被后台管理员取消给乘客时通知
            $req->setSmsTemplateCode("SMS_163430894");//模板ID
            $t="城际订单指派单被后台管理员取消给乘客";
        }
        elseif ($type==36){
            //$req->setSmsParam("{\"content\":\"" . $content . "\",\"product\":\"小马出行\"}"); //审核通知
            $req->setSmsTemplateCode("SMS_164268249");//模板ID
            $t="城际拼车开通活动推广";
        }
        elseif ($type==37){
            $coupon_price = $content['coupon_price'];
            $req->setSmsParam("{\"coupon_price\":\"" . $coupon_price . "\",\"product\":\"小马出行\"}"); //审核通知
            $req->setSmsTemplateCode("SMS_167525010");//模板ID
            $t="补发优惠券";
        }
        elseif ($type==38){
            $driver_name = $content['driver_name'];
            $car_plate = $content['car_plate'];
            $req->setSmsParam("{\"driver_name\":\"" . $driver_name . "\",\"car_plate\":\"" . $car_plate . "\",\"product\":\"小马出行\"}"); //  城际派单 改派时 给乘客 通知
            $req->setSmsTemplateCode("SMS_167402071");//模板ID
            $t="城际派单改派给乘客通知";
        }
        elseif ($type==39){
            $route = $content['route'];
            $start_time = $content['start_time'];
            $count = $content['passenger_number'];
            $req->setSmsParam("{\"line\":\"" . $route . "\",\"starttime\":\"" . $start_time . "\",\"count\":\"$count\",\"product\":\"小马出行\"}"); //  城际派单 改派时 给乘客 通知
            $req->setSmsTemplateCode("SMS_167974471");//模板ID
            $t="城际自动派单失败给客服短信通知";
        }
        elseif ($type==40){
            $number = $content['number'];
            $driver_name = $content['driver_name'];
            $driver_number = $content['driver_number'];
            $car_plate = $content['car_plate'];
            $start_time = $content['start_time'];
            $line = $content['line'];
            $req->setSmsParam("{\"number\":\"" . $number . "\",\"driver_name\":\"" . $driver_name . "\",\"driver_number\":\"". $driver_number ."\",\"car_plate\":\"" . $car_plate . "\",\"starttime\":\"" . $start_time . "\",\"line\":\"" .$line. "\",\"product\":\"小马出行\"}"); //  城际帮他人叫车 派单时 给乘车人 通知
            $req->setSmsTemplateCode("SMS_172525154");//模板ID
            $t="城际给他人叫车，给乘车人短信通知";
        }
        elseif ($type==41){
            $driver_name = $content['driver_name'];
            $driver_number = $content['driver_number'];
            $car_plate = $content['car_plate'];
            $start_time = $content['start_time'];
            $line = $content['line'];
            $req->setSmsParam("{\"driver_name\":\"" . $driver_name . "\",\"driver_number\":\"". $driver_number ."\",\"car_plate\":\"" . $car_plate . "\",\"starttime\":\"" . $start_time . "\",\"line\":\"" .$line. "\",\"product\":\"小马出行\"}"); //  城际帮他人叫车 改派订单时 给乘车人 通知
            $req->setSmsTemplateCode("SMS_172601657");//模板ID
            $t="城际给他人叫车，改派订单时给乘车人短信通知";
        }elseif ($type==42){
            $time = $content;
            $req->setSmsParam("{\"time\":\"" . $time . "\"}"); //  提现失败时通知
            $req->setSmsTemplateCode("SMS_173425873");//模板ID
            $t="司机账户封禁";
        }elseif ($type==43){
		    //派单老是不接，警告
            $time = $content;
            $req->setSmsParam("{\"time\":\"" . $time . "\"}"); //  提现失败时通知
            $req->setSmsTemplateCode("SMS_173425873");//模板ID
            $t="快车派单，司机多次不接单";
        }elseif ($type==44){
		    //变更手机号
            $req->setSmsParam("{\"number\":\"" . $phone . "\"}"); //  提现失败时通知
            $req->setSmsTemplateCode("SMS_178770261");//模板ID
        }
		$req->setRecNum($phone);//发送电话号码
		return $resp = $c->execute($req);
	}
   

	public static function StrToBin($str){
		//1.列出每个字符
		$arr = preg_split('/(?<!^)(?!$)/u', $str);
		//2.unpack字符
		foreach($arr as &$v){
			$temp = unpack('H*', $v);
			$v = base_convert($temp[1], 16, 2);
			unset($temp);
		}

		return join(' ',$arr);
	}

	public static function BinToStr($str){
		$arr = explode(' ', $str);
		foreach($arr as &$v){
			$v = pack("H".strlen(base_convert($v, 2, 16)), base_convert($v, 2, 16));
		}

		return join('', $arr);
	}

	/**
	 * 检查文件
	 * @param $file //文件
	 * @param $ext_rule //文件后缀规则
	 * @param $size //文件大小要求
	 * @return array
	 * */
	public static function checkFile($file,$ext_rule = '',$size = 200097152)
	{
		$status = 0;
		if(empty($file)){
			return array('status'=>$status,'msg'=>'文件异常');
		}
		$file_ext = strtolower(substr(strrchr($file['name'],'.'),1)) ;
		$ext = $ext_rule?:array('jpg', 'gif', 'png', 'jpeg');
		if(!in_array(strtolower($file_ext),$ext)){
			return array('status'=>$status,'msg'=>'格式不符合要求');
		}
		if($file['size']>$size){
			return array('status'=>$status,'msg'=>'大小超出要求');
		}
		switch ($file['error']){
			case 0:
				$status=1;
				$msg='ok';
				break;
			case 1:
				$msg = "大小超过了系统限制";
				break;
			case 2:
				$msg = "大小超过了页面限制";
				break;
			case 3:
				$msg = "只有部分被上传";
				break;
			case 4:
				$msg = "未被上传";
				break;
			case 6:
				$msg = "找不到临时文件夹";
				break;
			case 7:
				$msg = "写入失败";
				break;
		}
		return array('status'=>$status,'msg'=>$msg);
	}

	/**
	 * 截取指定长度字符串，中英混合皆可
	 * @param $str //需截取的字符串
	 * @param $start //截取起始位
	 * @param $length //截取长度
	 * @param $tail //省略的替代字符串
	 * @param $encoding //指定字符串编码
	 * @return false|string
	 * */
	public static function mb_truncate($str='',$start=0,$length=10,$tail='...',$encoding='utf8'){
		if(!$str){
			return false;
		}
		if(mb_strlen($str,'UTF-8')<=$length){
			return $str;
		}else{
			$substr = mb_substr($str, $start, $length, $encoding);
			return $substr.$tail;
		}
	}

	/**
	 * 支付宝支付api
	 * @param string
	 * @param int
	 * @param string
	 * @return array|object|string 成功时返回
	 */
	public static function alipayApi($config,$order_sn,$need_price){
		$aop = new AopClient;
		$aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
		$aop->appId = $config['appId'];
		$aop->rsaPrivateKey = $config['rsaPrivateKey'];
		$aop->format = "json";
		$aop->charset = "UTF-8";
		$aop->signType = "RSA2";
		//       $aop->alipayrsaPublicKey = '请填写支付宝公钥，一行字符串';
		$aop->alipayrsaPublicKey = $config['alipayrsaPublicKey'];
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		$alipay_request = new AlipayTradeAppPayRequest();//
		//SDK已经封装掉了公共参数，这里只需要传入业务参数
		$param["body"] = $config['body'];
		$param["subject"] = "App支付";
		$param["out_trade_no"] = $order_sn;
		$param["total_amount"] = $need_price;
		$param["timeout_express"] = "30m";
		$param["product_code"] = "QUICK_MSECURITY_PAY";
		$config["passback_params"]&&$param["passback_params"] = urlencode(json_encode($config["passback_params"]));
		$bizcontent = json_encode($param);
		$alipay_request->setNotifyUrl($config['setNotifyUrl']);
		$alipay_request->setBizContent($bizcontent);
		//这里和普通的接口调用不同，使用的是sdkExecute
		$response = $aop->sdkExecute($alipay_request);
		//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
		//   $data = htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。
		return $response;

	}

	/**
	 * 微信支付
	 * @param array
	 * @param string
	 * @param int
	 * @return array 成功时返回
	 */
	public static function wxPayApi($config,$order_sn,$need_price){
		$appid = $config['appid'];
		$mch_id = $config['mch_id'];
		$notify_url = $config['notify_url'];
		$key = $config['key'];
		//1.统一下单方法
		$wechatAppPay = new wechatAppPay($appid, $mch_id, $notify_url, $key);
		$params['body'] = '小马出行-用户充值'; //商品描述
		$params['out_trade_no'] = $order_sn;//的订单号
		$params['total_fee'] = $need_price;//订单金额 只能为整数 单位为分
		$params['trade_type'] = 'APP'; //交易类型 JSAPI | NATIVE | APP | WAP
		$config['attach']&&$params['attach'] = $config['attach'];//附加数据
		$result = $wechatAppPay->unifiedOrder( $params );
		if(strtoupper($result['result_code'])=='FAIL'){
			return array('status'=>0,'msg'=>$result['err_code_des']);
		}
		//2.创建APP端预支付参数
		return $wechatAppPay->getAppPayParams($result['prepay_id']);
	}
	/**
	 * 小程序微信支付
	 * @param string
	 * @param int
	 * @return array 成功时返回
	 */
	public function xiaochengxu_wechatApi($config,$order_sn,$need_price,$openid)
	{
		$appid = "wx26bfa6f22e1432e4";//小程序的appid
		$mch_id = $config['mch_id'];
		$notify_url = $config['notify_url'];
		$key = $config['key'];

		//1.统一下单方法
		$wechatAppPay = new wechatAppPay($appid, $mch_id, $notify_url, $key);
		$params['body'] = '小马出行-用户充值'; //商品描述
		$params['out_trade_no'] = $order_sn;//的订单号
		$params['openid'] = $openid;//用户的openid
		$params['total_fee'] = intval($need_price);//订单金额 只能为整数 单位为分
		$params['trade_type'] = 'JSAPI'; //交易类型 JSAPI | NATIVE | APP | WAP
		$result = $wechatAppPay->xiaochengxu_unifiedOrder($params);
		//2.创建APP端预支付参数
		return $wechatAppPay->getAppPayParams_xiaochengxu($result['prepay_id']);
	}
	public static function getIp(){
		if (getenv('HTTP_CLIENT_IP')) {
			$ip = getenv('HTTP_CLIENT_IP');
		}
		elseif (getenv('HTTP_X_FORWARDED_FOR')) { //获取客户端用代理服务器访问时的真实ip 地址
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_X_FORWARDED')) {
			$ip = getenv('HTTP_X_FORWARDED');
		}
		elseif (getenv('HTTP_FORWARDED_FOR')) {
			$ip = getenv('HTTP_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_FORWARDED')) {
			$ip = getenv('HTTP_FORWARDED');
		}
		else if(!empty($_SERVER["REMOTE_ADDR"])){
			$ip = $_SERVER["REMOTE_ADDR"];
		}else{
			$ip = "unknown";
		}
		return $ip ;
	}

	/**
	利用淘宝的ip地址库获获取ip + 地址
	 */
	public static function get_ip_dizhi(){
		$opts = array(
			'http'=>array(
				'method'=>"GET",
				'timeout'=>5,)
		);
		$context = stream_context_create($opts);
		$ipmac=self::getIp();
		if(strpos($ipmac,"127.0.0.") === true)return '';
		$url_ip='http://ip.taobao.com/service/getIpInfo.php?ip='.$ipmac;
		$str = @file_get_contents($url_ip, false, $context);
		if(!$str) return "";
		$json=json_decode($str,true);
		$ipcity = '';
		$total = '';
		if($json['code']==0){
			$ipcity= $json['data']['region'].$json['data']['city'];
			$total= $json['data'];
		}
		return array('total'=>$total,'address'=>$ipcity,'ip'=>$ipmac);
	}

	/**
	 * 处理文件，将多数组形式变成键值对形式
	 * @param $files
	 * @return array
	 * */
	public static function dealFile($files)
	{
		$fileArray = array();
		foreach ($files as $k => $file){
			if(is_array($file['name'])) {
				$keys = array_keys($file);
				$count	 =	 count($file['name']);
				for ($i=0; $i<$count; $i++) {
					foreach ($keys as $key)
						$fileArray[$k][$i][$key] = $file[$key][$i];
				}
			}else{
				$fileArray[$k] = $file;
			}
		}
		return $fileArray;
	}

	/**
	 * 文件日志，用于观察错误
	 * @param $log
	 * @param $file_name
	 * @param $type
	 * @param $encode_type //城内和城际加密方式不同
	 * @param $key
	 * */
	public static function fileLog($log,$file_name="./post_receive_log.txt",$type='receive',$encode_type = 'inner',$key='xmcx0551'){
		$content = date('Y-m-d H:i:s').'#';
		$content .= self::mobileOS().'#';
		$content .= '/'.MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME.'#';
		$file_name = $file_name?:"./post_receive_log.txt";
		$type = $type?:"receive";
		$encode_type = $encode_type?:"inner";
		$key = $key?:"xmcx0551";
		switch ($encode_type){
			case 'inter':
				$des=JoDES::share();
				$content = date('Y-m-d H:i:s').'#';
				$content .= mobileOS().'#';
				$content .= '/'.GROUP_NAME.'/'.MODULE_NAME.'/'.ACTION_NAME.'#';
				switch ($type){
					case 'send':
						$content .= 'send='.$des->encode($log,$key)."***";
						$content .= 'send_decode='.$des->decode($log,$key)."\r\n";
						break;
					case 'receive':
						$content .= "receive=".$log."***";
						$content .= 'receive_decode='.$des->decode($log,$key)."\r\n";
						break;
					default :
						$content .= "$type=".json_encode($log)."***";
						break;

				}
				break;
			default:
				switch ($type){
					case 'send':
						$content .= 'send='.$log."***";
						$content .= 'send_decode='.Security::decrypt($log)."\r\n";
						break;
					default:
						$content .= "encode=".json_encode($log)."***";
						$content .= $type.'_decode='.Security::decrypt($log)."\r\n";
						break;
				}
				break;
		}
		file_put_contents($file_name,$content,FILE_APPEND);
	}

	/**
	 * 判断手机的操作系统
	 * @return string
	 * */
	public static function mobileOS()
	{
		//全部变成小写字母
		$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
		$type = 'other';
		//分别进行判断
		if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
		{
			$type = 'ios';
		}
		if(strpos($agent, 'android'))
		{
			$type = 'android';
		}
		return $type;
	}

	/**
	 * 记录服务端和App端数据传输
	 * @param $data //数据内容
	 * @param $type
	 * @param $data_type //1为发送，2为接收
	 * @return boolean
	 * */
	public static function dataLog($data,$type='send',$data_type=1)
	{
		if(empty($data)){
			return false;
		}
		$content['request_time']=date('Y-m-d H:i:s');
		$content['OS']=self::mobileOS();
		$content['WEB']='/'.MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME;
		switch ($type){
			case 'send':
				$content['send_decode'] = $data;
				$content['send_encode'] = '["' . Security::encrypt(json_encode($data)) . '"]';
				$data_['type'] = 1;
				break;
			case 'receive':
				$content['receive_decode'] = Security::decrypt($data);
				$content['receive_encode'] = $data;
				$data_['type'] = 2;
				break;
			default:
				$content[$type.'_decode_1'] = $content[$type.'_encode_2'] =$data;
				$content[$type.'_decode_2'] = Security::decrypt($data);
				$content[$type.'_encode_1'] = '["' . Security::encrypt(json_encode($data)) . '"]';
				$data_['type'] = $data_type;
				break;
		}
		$data_['content'] = json_encode($content);
		db('transfer_data_record',config('inner_db'))->insert($data_);
		return true;
	}

	/**
	 * 微信退款--20180910转用java
	 * @param array
	 * @param string
	 * @param int
	 * @param string
	 * @param int
	 * @return array|string 成功时返回
	 */
	public static function wxRefundScrap($config,$order_sn,$need_price,$refund_sn,$refund_fee)
	{
		$appid = $config['appid'];
		$mch_id = $config['mch_id'];
		$notify_url = $config['notify_url'];
		$key = $config['key'];
		$cert_path = $config['sslcert_path'];
		$key_path = $config['sslkey_path'];
		$wechatAppPay = new wechatAppPay($appid, $mch_id, $notify_url, $key,$cert_path,$key_path);
		$params['out_trade_no'] = $order_sn;//付款的订单号
		$params['out_refund_no'] = $refund_sn;//退款的订单号
		$params['total_fee'] = $need_price;//订单金额 只能为整数 单位为分
		$params['refund_fee'] = $refund_fee;//需要退款的金额 只能为整数 单位为分
		$result = $wechatAppPay->refund( $params );
		return $result;
	}

	/**
	 * 支付宝退款--20180910转用java
	 * @param array
	 * @param string
	 * @param string
	 * @param int
	 * @return array|string
	 */
	public static function aliRefundScrap($config,$order_sn,$refund_sn,$refund_money){

		$aop = new AopClient;
		$aop->appId = $config['appId'];
		$aop->rsaPrivateKey = $config['rsaPrivateKey'];
		$aop->signType = "RSA2";
		$aop->alipayrsaPublicKey = $config['alipayrsaPublicKey'];
		$aop->alipayPublicKey = $config['alipayPublicKey'];
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		$alipay_request = new AlipayTradeRefundRequest();//
		//SDK已经封装掉了公共参数，这里只需要传入业务参数
		$param["out_trade_no"] = $order_sn;
		$param["out_request_no"] = $refund_sn;
		$param["refund_amount"] = $refund_money;
		$bizcontent = json_encode($param);
		$alipay_request->setNotifyUrl($config['setNotifyUrl']);
		$alipay_request->setBizContent($bizcontent);
		$result = $aop->execute($alipay_request);
		$responseNode = str_replace(".", "_", $alipay_request->getApiMethodName()) . "_response";
		return (array)$result->$responseNode;
	}

	/**
	 * 微信退款查询--20180910转用java
	 * @param array
	 * @param string
	 * @return array|string 成功时返回
	 * */
	public static function wxRefundQueryScrap($config,$refund_sn)
	{
		$appid = $config['appid'];
		$mch_id = $config['mch_id'];
		$notify_url = $config['notify_url'];
		$key = $config['key'];
		$wechatAppPay = new wechatAppPay($appid, $mch_id, $notify_url, $key);
		$params['out_refund_no'] = $refund_sn;//退款的订单号
		$result = $wechatAppPay->refundQuery( $params );
		return $result;
	}

	/**
	 * 支付宝退款查询--20180910转用java
	 * @param array
	 * @param string
	 * @param string
	 * @return array|string 成功时返回
	*/
	public static function aliRefundQueryScrap($config,$order_sn,$refund_sn)
	{
		$aop = new AopClient ();
		$aop->appId = $config['appId'];
		$aop->rsaPrivateKey = $config['rsaPrivateKey'];
		$aop->alipayrsaPublicKey=$config['alipayrsaPublicKey'];
		$aop->alipayPublicKey = $config['alipayPublicKey'];
		$aop->signType = 'RSA2';
		$request = new AlipayTradeFastpayRefundQueryRequest();
		$param["out_trade_no"] = $order_sn;
		$param["out_request_no"] = $refund_sn;
		$bizcontent = json_encode($param);
		$request->setBizContent($bizcontent);
		$result = $aop->execute ( $request);
		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		return (array)$result->$responseNode;
	}

	/**
	 * 生成缩略图，返回$_FILES的格式
	 * @param array
	 * @return array
	 * */
	public static function thumb($files)
	{
		$data = array();
		foreach ($files as $key => $value) {
			$tmp_name = $value['tmp_name'];
			$ext = substr(strrchr($value['name'],'.'),1);//文件后缀
			$rand = rand(100, 999);
			$file_rand_name = date("YmdHis").$rand.'.'.$ext;//缩略图文件名
			//类型下面的日期文件夹
			$image = \think\Image::open($tmp_name);
			$path = ROOT_PATH."/public/thumb";
			if(!is_dir($path)){
				mkdir($path,0777,true);
			}
			$image->thumb(150, 150)->save($path.'/'.$file_rand_name);
			$data[$key.'_thumb']['tmp_name'] = $path.'/'.$file_rand_name;
			$data[$key.'_thumb']['name'] = $value['name'];
		}
		return $data;
	}

	/**
	 * excel表格导出
	 * @param string $fileName 文件名称
	 * @param array $headArr 表头名称
	 * @param array $data 要导出的数据
	 * @author static7  */
	public static function excelExport($fileName = '', $headArr = [], $data = []) {
		Loader::import('PHPExcel.PHPExcel', EXTEND_PATH);
		Loader::import('PHPExcel.PHPExcel.IOFactory',EXTEND_PATH);
		$fileName .= "_" . date("Y_m_d", time()) . ".xls";
		$objPHPExcel = new \PHPExcel();
		$objPHPExcel->getProperties();
		//$key = ord("A"); // 设置表头
        $ordA = ord('A'); //65
        $key2 = ord("@"); //64
		foreach ($headArr as $v) {
            if($ordA > ord("Z")){
                $colum = chr(ord("A")).chr(++$key2);//超过26个字母 AA1,AB1,AC1,AD1...BA1,BB1...
            }else{
                $colum = chr($ordA++);
            }
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $objPHPExcel->getActiveSheet()->getColumnDimension($colum)->setWidth('20');
            $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
			//$key += 1;
		}
		$column = 2;
		$objActSheet = $objPHPExcel->getActiveSheet();
		foreach ($data as $key => $rows) { // 行写入
			$span = ord("A");
            $kll  = ord("@"); //64
			foreach ($rows as $keyName => $value) { // 列写入
                if($span > ord("Z")){
                    $columll = chr(ord("A")).chr(++$kll);//超过26个字母 AA1,AB1,AC1,AD1...BA1,BB1...
                }else{
                    $columll = chr($span++);
                }
				$objActSheet->setCellValue($columll . $column, " ".$value);
			}
			$column++;
		}
		$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
		$objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
		header('Content-Type: application/vnd.ms-excel');
		header("Content-Disposition: attachment;filename=$fileName");
		header('Cache-Control: max-age=0');
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output'); // 文件通过浏览器下载
		exit();
	}

	/*
	 * PHPEXCEL 导入操作
	*/
	public static function excelImport($files=[]){
        Loader::import('PHPExcel.PHPExcel', EXTEND_PATH);
        Loader::import('PHPExcel.PHPExcel.IOFactory',EXTEND_PATH);
        $ext = substr(strrchr($files['file']['name'],'.'),1);                       //文件后缀
        if (strtolower($ext) != "xls" && strtolower($ext) != "xlsx") {
            return ['status'=>0,'msg'=>'不是Excel文件,请重新操作'];die;
        }
        $tmp_name = $files['file']['tmp_name'];
        $rand = rand(100, 999);
        $file_rand_name = date("YmdHis").$rand.'.'.$ext;                                   //文件名
        //类型下面的日期文件夹
        //$image = \think\Image::open($tmp_name);
        $path = ROOT_PATH."/public/excel";
        if(!is_dir($path)){
            mkdir($path,0777,true);
        }
        $result = move_uploaded_file($tmp_name,$path.'/'.$file_rand_name);
        if(empty($result)){
            return ['status'=>0,'msg'=>'导入数据失败'];die;
        }
        $file_name = $path.'/'.$file_rand_name;
        $readerType = ($ext == ".xlsx") ? "Excel2007" : "Excel5";
        $objReader = \PHPExcel_IOFactory::createReader($readerType)->load( $file_name );
        $sheet = $objReader->getSheet( 0 );
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumn = $sheet->getHighestColumn(); // 取得总列数
        if(strlen($highestColumn)>1) {
            $highestColumn = 'Z';
        }
        $colspan = range( 'A', $highestColumn );
        for ( $j = 2; $j <= $highestRow; $j++ ) {
            $array = array( );
            foreach ( $colspan as $value ) {
                $array[] = $objReader->getActiveSheet()->getCell( $value . $j )->getValue();
            }
            $datas['CHILD'][] = $array;
        }
        unlink($file_name);
        $datas['status']    = 1;
        $datas['msg']       = '导入成功';
        return $datas;
    }

	/**
	 * 清除缓存
	 * @param array
	 * */
	public static function clearCache($data)
	{
		if($data){
			foreach ($data as $val){
				Cache::rm($val);
			}
		}
	}

	/**
	 * 生成二维码
	 * @param $value//二维码的值
	 * @param $path//二维码图片路径(本地临时路径)
	 * @param $file_name//二维码图片路径(文件服务器路径)
	 * @param $errorCorrectionLevel//容错级别
	 * @param $matrixPointSize//二维码尺寸大小
	 * param $matrixMarginSize//生成二维码的边距
	 * @return array
	 * */
	public static function makeQRCode($value,$path,$file_name,$errorCorrectionLevel='L',$matrixPointSize = 6,$uid=''){
		if(empty($value) || empty($path) || empty($file_name)){
			return array('status'=>0,'msg'=>'参数异常');
		}
		//include_once "../phpqrcode.php";
		//$object = new \QRcode();
		QRcode::png($value, $path, $errorCorrectionLevel, $matrixPointSize, 2);
		$QR['qr_code']['name'] = array_pop(explode('/',$path));
		$QR['qr_code']['tmp_name'] = $path;
		$ftp = new FTP('','','','','WEB');
		$s = $ftp->ftpUploads($QR,$file_name,$uid);
		unlink($path);
		if(!$s['status']){
			return $s;
		}
		return array('status'=>1,'qr_code'=>$s['data']['qr_code']);
	}

	/**
	 * 内部推送消息
	 * @param $data
	 * @return  array
	 * */
	public static function innerPush($data)
	{
		include_once 'socket_param.php';
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $socket['inner_http_use'] );
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
		curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
		$return = curl_exec ( $ch );
		curl_close ( $ch );
		return $return;
	}

	/**
	 * 绑定私密号--调用java接口
	 * @param $phoneA
	 * @param $phoneB
	 * @param $expire
	 * @param $record
	 * @param $outId
	 * @return  mixed
	 * */
	public static function AXBBind($phoneA,$phoneB,$expire,$common_id,$record=false,$outId=0)
	{
		if(empty($phoneA) || empty($phoneB) || empty($expire)){
			return false;
		}
		$data['encode'] = Security::encrypt("common_id={$common_id}&phoneA={$phoneA}&phoneB={$phoneB}&expiration={$expire}&outId={$outId}");
		return json_decode(Security::decrypt(https_request(Env::get('axbBind'.ENV.'_url'),$data)),true);
	}

	/**
	 * 解绑私密号--调用java接口
	 * @param $subsId
	 * @param $secretNo
	 * @return mixed
	 * */
	public static function AXBUnbind($subsId,$secretNo)
	{
		if(empty($subsId) || empty($secretNo)){
			return false;
		}
		$data['encode'] = Security::encrypt("subsId=$subsId&secretNo=$secretNo");
		return json_decode(Security::decrypt(https_request(Env::get('axbUnbind'.ENV.'_url'),$data)),true);
	}

	/**
	 * 极光推送--调用java接口
	 * @param $title
	 * @param $content
	 * @param $id //多个用户以逗号分割
	 * @param $type //user,innerDriver,interDriver
	 * @return mixed
	 * */
	public static function JPush($title,$content,$id,$type,$sendType)
	{
		if(empty($title) || empty($content) || empty($id) || empty($type)){
			return false;
		}
		if(is_array($id)){
			$id = implode(',',$id);
		}
		$info = array('type'=>'driver','registration_id'=>$id,'driver_id'=>'','uid'=>'','auth_status'=>'','sendType'=>$sendType);


		if($type == 'user'){
			sendjg($info, $title, $content,1);
		}else{
			sendjg($info, $title, $content,2);
		}

//	    $data['encode'] = Security::encrypt("title=$title&content=$content&jgIdStr=$id&type=$type");
//	    return json_decode(Security::decrypt(https_request(Env::get('JPush'.ENV.'_url'),$data)),true);
	}

	/**
	 * 发送短信--调用java接口
	 * @param $phone
	 * @param $content //短信内容
	 * @param $type //短信模板对应内容
	 * @return mixed
	 */
	public static function msg($phone,$content=array(),$type)
	{
        return 1;
		if ($type == 1) {
			$body = json_encode(array('code'=>$content,'product'=>'小马出行'));
			$model_id = "SMS_66680212";
			//$t="验证码";
		} elseif ($type == 2) {
			$body = json_encode(array('starttime'=>$content['starttime'],'startaddress'=>$content['startaddress']));
			$model_id = "SMS_66730335";
			// $t="通知司机新订单";
		} elseif ($type == 3) {
			$body = json_encode(array('starttime'=>$content['starttime'],'startaddress'=>$content['startaddress'],'count'=>$content['count']));
			$model_id = "SMS_66765395";
			//$t="通知客服新订单";
		} elseif ($type == 4) {
			//请注意有上车扫码的乘客退单，订单号为:${osn}
			$body = json_encode(array('osn'=>$content['osn']));
			$model_id = "SMS_66685361";
			// $t="通知客服上车付款退单";
		} elseif ($type == 5) {
			//通知客服付款后的退单
			$body = json_encode(array('osn'=>$content['osn']));
			$model_id = "SMS_66835351";
		} elseif ($type == 6) {
			//通知客服付款后的退单
			$body = json_encode(array('xmcoupon'=>$content['money']));
			$model_id = "SMS_69750157";
			// $t="通知乘客优惠券";
		} elseif ($type == 7) {
			//通知客服付款后的退单
			$body = json_encode(array('name'=>$content['name']));
			$model_id = "SMS_70075337";
			//$t="通知司机招募";
		} elseif ($type == 8) {
			//通知客服新订单
			$body = json_encode(array('month'=>$content['month'],'day'=>$content['day'],'hour'=>$content['hour'],'minute'=>$content['minute'],'name'=>$content['name'],'price'=>$content['price'],'money'=>$content['money']));
			$model_id = "SMS_73805011";
			//$t="通知司机奖励";
		}elseif ($type == 9) {
			//审核通知
			$body = json_encode(array('driver'=>$content,'product'=>'小马出行'));
			$model_id = "SMS_118765058";
			//$t="司机认证审核通过";
		}
		elseif ($type == 10) {
			$body = json_encode(array('driver'=>$content,'product'=>'小马出行'));
			$model_id = "SMS_118560060";
			//$t="司机认证审核未通过";
		}
		elseif ($type == 11) {
			$body = json_encode(array('driver'=>$content,'product'=>'小马出行'));
			$model_id = "SMS_123485012";
			//$t="教练提交资料通知";
		}
		elseif ($type == 12) {
			$body = json_encode(array('driver'=>$content,'product'=>'小马出行'));
			$model_id = "SMS_123305017";
			//$t="司机认证审核通过";
		}
		elseif ($type == 13) {
			$body = json_encode(array('driver'=>$content,'product'=>'小马出行'));
			$model_id = "SMS_123310024";
			//$t="司机认证审核未通过";
		}
		elseif ($type==14){
			$body = json_encode(array('driver'=>$content,'product'=>'小马出行'));
			$model_id = "SMS_124315030";
			$t="网约车司机提交资料成功提醒";
		}
		elseif ($type==15){
			$body = json_encode(array('driver'=>$content['name'],'password'=>$content['password'],'product'=>'小马出行'));
			$model_id = "SMS_124360041";
			$t="司机审核认证通过";
		}
		elseif ($type==16){
			$body = json_encode(array('driver'=>$content,'product'=>'小马出行'));
			$model_id = "SMS_124420033";
			$t="司机审核认证未通过";
		}
		elseif ($type==17){//给报警人发送
			$body = json_encode(array('phone'=>$phone,'product'=>'小马出行'));
			$model_id = "SMS_125930007";
			$t="乘客紧急求助已成功短信提醒";
		}
		elseif ($type==18){//给后台客服发送短信提醒
			$body = json_encode(array('phone'=>$content,'product'=>'小马出行'));
			$model_id = "SMS_125740009";
			$t="一键报警信息提醒";
		}
		elseif ($type==20){//给后台客服发送短信提醒
			$body = json_encode(array('phone'=>$phone,'name'=>$content,'product'=>'小马出行'));
			$model_id = "SMS_125765019";
			$t="投诉反馈信息提醒";
		}
		elseif ($type==21){//给后台客服发送短信提醒
			$body = json_encode(array('phone'=>$phone,'product'=>'小马出行'));
			$model_id = "SMS_126035058";
			$t="系统自动取消订单信息提醒";
		}
		elseif ($type==22){//给推荐人发送短信通知领取礼品(驾校招生)
			$body = json_encode(array('phone'=>$content['phone'],'name'=>$content['name'],'product'=>'小马出行'));
			$model_id = "SMS_128490031";
			$t="给推荐人发送短信通知领取礼品";
		}
		$data['encode'] = Security::encrypt("phoneNumber=$phone&content=$body&code=$model_id");
		return json_decode(Security::decrypt(https_request(Env::get('Msg'.ENV.'_url'),$data)),true);
	}

	/**
	 * 微信退款查询--调用java接口
	 * @param array
	 * @param string
	 * @return array|string 成功时返回
	 * */
	public static function wxRefundQueryJava($refund_sn)
	{
		if(empty($refund_sn)){
			return array('status'=>0,'msg'=>'退款号为空');
		}
		$data['encode'] = Security::encrypt("outRefundNo=$refund_sn");
		return json_decode(Security::decrypt(https_request(Env::get('wxRefund'.ENV.'_query'),$data)),true);
	}

	/**
	 * 微信退款--调用java接口
	 * @param array
	 * @param string
	 * @param int
	 * @param string
	 * @param int
	 * @return array|string 成功时返回
	 */
	public static function wxRefundJava($order_sn,$need_price,$refund_sn,$refund_fee)
	{
		if(empty($order_sn) || empty($need_price) || empty($refund_sn) || empty($refund_fee)){
			return array('status'=>0,'msg'=>'缺少参数');
		}
		$data['encode'] = Security::encrypt("outTradeNo=$order_sn&outRefundNo=$refund_sn&totalFee=$need_price&refundFee=$refund_fee");
		return json_decode(Security::decrypt(https_request(Env::get('wxRefund'.ENV.'_url'),$data)),true);
	}

	/**
	 * 支付宝退款查询--调用java接口
	 * @param array
	 * @param string
	 * @param string
	 * @return array|string 成功时返回
	 */
	public static function aliRefundQueryJava($order_sn,$refund_sn)
	{
		if(empty($refund_sn)|| empty($order_sn)){
			return array('status'=>0,'msg'=>'缺少参数');
		}
		$data['encode'] = Security::encrypt("outTradeNo=$order_sn&outRequestNo=$refund_sn");
		return json_decode(Security::decrypt(https_request(Env::get('aliRefund'.ENV.'_query'),$data)),true);
	}

	/**
	 * 支付宝退款--调用java接口
	 * @param array
	 * @param string
	 * @param string
	 * @param int
	 * @return mixed
	 */
	public static function aliRefundJava($order_sn,$refund_sn,$refund_money)
	{
		if(empty($order_sn) || empty($refund_sn) || empty($refund_money)){
			return array('status'=>0,'msg'=>'缺少参数');
		}
		$data['encode'] = Security::encrypt("outTradeNo=$order_sn&outRequestNo=$refund_sn&refundAmount=$refund_money");
		return json_decode(Security::decrypt(https_request(Env::get('aliRefund'.ENV.'_url'),$data)),true);
	}
	/**
	 * 阿里云OSS服务器上传
	 filename 文件名称,localname,本地地址,eg /usr/local/abc.txt
	 * @param string
	 * @param int
	 * @return string 成功时返回
	 */
	public function aliUpload($filename,$localname){
		if (is_file(__DIR__ . '/../autoload.php')) {
		    require_once __DIR__ . '/../autoload.php';
		}
		if (is_file(__DIR__ . '/../vendor/autoload.php')) {
		    require_once __DIR__ . '/../vendor/autoload.php';
		}
		// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
		$accessKeyId = "LTAIO5Mh44ygOuMt";
		$accessKeySecret = "A21EPAyETIe93JEUnmzFAJRQqEUwaD";
		// Endpoint以杭州为例，其它Region请按实际情况填写。
		$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
		// 存储空间名称
		$bucket= "xmfreeride";
		// 文件名称
		$object = $filename;
		// <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt
		$filePath = $localname;
		try{
		    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
		    $ossClient->uploadFile($bucket, $object, $filePath);
		    return ['status'=>1,'msg'=>'ok'];
		} catch(OssException $e) {
		    //printf(__FUNCTION__ . ": FAILED\n");
		    //printf($e->getMessage() . "\n");
		    return ['status'=>0,'msg'=>$e->getMessage()];
		}
		//print(__FUNCTION__ . ": OK" . "\n");
	}

    /**
     * 向公安部提交请求
     * @param string
     * @param int
     * @return string 成功时返回
     */
    public static function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;

        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_TIMEOUT,5);   //只需要设置一个秒的数量就可以
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }


    /**
     * @param $phone
     * @return int
     * 手机运营商检测
     */
    public static function phone_check($phone)
    {

        $isPhone = "/^1[3-9]\d{9}$/"; //先判断正确手机号格式

        if (preg_match($isPhone, $phone)) {

            $isChinaMobile = "/^134[0-9]\d{7}$|^1703\d{7}$|^170[5-6]\d{7}$|^(?:13[5-9]|147|148|15[0-27-9]|178|18[2-478]|198)\d{8}$/"; //
            $isChinaUnion  = "/^1704\d{7}$|^170[7-9]\d{7}$|^171[0-9]\d{7}$|^(?:13[0-2]|145|15[56]|166|140|175|176|18[56])\d{8}$/"; //
            $isChinaTelcom = "/^(?:133|153|169|177|173|174|170|179|18[019]|199)\d{8}$|^170[0-2]\d{7}$/"; //

            if (preg_match($isChinaUnion, $phone)) {

                return 1; //中国联通
            } else if (preg_match($isChinaMobile, $phone)) {

                return 2; //中国移动
            } else if (preg_match($isChinaTelcom, $phone)) {

                return 3; //中国电信
            } else {
                return 4; //其他
            }

        } else {
            return 4;

        }
    }

    //将下划线命名转换为驼峰式命名
    public static function convertUnderline( $str , $ucfirst = false)
    {
        $str = ucwords(str_replace('_', ' ', $str));
        $str = str_replace(' ','',lcfirst($str));

        return $ucfirst ? ucfirst($str) : $str;
    }

}
